{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "a2e0aa59",
   "metadata": {},
   "source": [
    "# Test Voice Activity Detection (VAD)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9aac6a45",
   "metadata": {},
   "outputs": [],
   "source": [
    "%load_ext autoreload\n",
    "%autoreload 2\n",
    "\n",
    "import os\n",
    "import sys\n",
    "os.chdir('../..')\n",
    "sys.path.insert(1, os.path.join(sys.path[0], '../..'))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "50791891",
   "metadata": {},
   "outputs": [],
   "source": [
    "import soundfile as sf\n",
    "import IPython.display as ipd\n",
    "\n",
    "file = 'data/voxceleb1/id10001/1zcIwhmdeo4/00001.wav'\n",
    "\n",
    "audio, sr = sf.read(file, dtype='int16')\n",
    "\n",
    "ipd.display(ipd.Audio(audio, rate=sr))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d8bf0ecd",
   "metadata": {},
   "outputs": [],
   "source": [
    "from VAD import VAD\n",
    "\n",
    "vad = VAD(threshold=-20)\n",
    "\n",
    "output = vad.apply(audio, sr)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5d982646",
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "\n",
    "def plot_vad(data, titles, sr):\n",
    "    plt.subplots(len(data), 1, figsize=(20, 10))\n",
    "    plt.subplots_adjust(hspace=0.5)\n",
    "\n",
    "    for i in range(len(data)):\n",
    "        plt.subplot(len(data), 1, i + 1)\n",
    "        y = data[i]\n",
    "        x = [i / sr for i in range(0, len(y))]\n",
    "        plt.plot(x, y)\n",
    "        plt.gca().set_title(titles[i])\n",
    "\n",
    "    plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6ea90cdd",
   "metadata": {},
   "outputs": [],
   "source": [
    "plot_vad(\n",
    "    data=[audio, vad.last_energy, vad.last_vad, output],\n",
    "    titles=[\n",
    "        'Input signal',\n",
    "        'Short time energy',\n",
    "        'Voice activity detection',\n",
    "        'Output signal'\n",
    "    ],\n",
    "    sr=sr\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "99670a9e",
   "metadata": {},
   "outputs": [],
   "source": [
    "vad.last_vad.mean()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bd30014d",
   "metadata": {},
   "outputs": [],
   "source": [
    "audio.shape, output.shape"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
